package services

import (
	"booking-service/internal/models"
	"booking-service/internal/storage/memory"
	log "github.com/sirupsen/logrus"
	"testing"
	"time"
)

func initializeRoomAvailability(storage *memory.InMemoryRoomAvailabilityStorage) error {
	var err error

	err = storage.UpdateAvailability("reddison", "lux", time.Date(2024, 1, 2, 0, 0, 0, 0, time.UTC), 1)
	if err != nil {
		log.Errorf("Failed to update availability for 2024-01-02: %v", err)
		return err
	}

	err = storage.UpdateAvailability("reddison", "lux", time.Date(2024, 1, 3, 0, 0, 0, 0, time.UTC), 1)
	if err != nil {
		log.Errorf("Failed to update availability for 2024-01-03: %v", err)
		return err
	}

	err = storage.UpdateAvailability("reddison", "lux", time.Date(2024, 1, 4, 0, 0, 0, 0, time.UTC), 1)
	if err != nil {
		log.Errorf("Failed to update availability for 2024-01-04: %v", err)
		return err
	}

	return nil
}

func TestCreateOrder(t *testing.T) {
	orderStorage := &memory.InMemoryOrderStorage{}
	roomStorage := memory.NewInMemoryRoomAvailabilityStorage()
	bookingService := NewBookingService(orderStorage, roomStorage)

	// Инициализация доступности номеров
	err := initializeRoomAvailability(roomStorage)
	if err != nil {
		t.Fatalf("Failed to initialize room availability: %v", err)
	}

	newOrder := models.Order{
		HotelID:   "reddison",
		RoomID:    "lux",
		UserEmail: "guest@mail.ru",
		From:      time.Date(2024, 1, 2, 0, 0, 0, 0, time.UTC),
		To:        time.Date(2024, 1, 3, 0, 0, 0, 0, time.UTC),
	}

	err = bookingService.CreateOrder(newOrder)
	if err != nil {
		t.Errorf("Failed to create order: %v", err)
	}

	availability, _ := roomStorage.GetAvailability("reddison", "lux", time.Date(2024, 1, 2, 0, 0, 0, 0, time.UTC))
	if availability.Quota != 0 {
		t.Errorf("expected quota to be 0, got %d", availability.Quota)
	}
}

func TestCreateOrderRoomNotAvailable(t *testing.T) {
	orderStorage := &memory.InMemoryOrderStorage{}
	roomStorage := memory.NewInMemoryRoomAvailabilityStorage()
	bookingService := NewBookingService(orderStorage, roomStorage)

	newOrder := models.Order{
		HotelID:   "reddison",
		RoomID:    "lux",
		UserEmail: "guest@mail.ru",
		From:      time.Date(2024, 1, 5, 0, 0, 0, 0, time.UTC),
		To:        time.Date(2024, 1, 6, 0, 0, 0, 0, time.UTC),
	}

	err := bookingService.CreateOrder(newOrder)
	if err == nil {
		t.Errorf("expected error, got nil")
	}
}
